using GatewaySwagger;
using GatewaySwagger.Jwt;
using GatewayUI;
using Microsoft.Extensions.Options;
using Ocelot.Cache.CacheManager;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
using Ocelot.Provider.Polly;

var builder = WebApplication.CreateBuilder(args);

var env = builder.Environment;

var conf = builder.Configuration;

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//多ocelot配置文件合并
builder.Configuration
      .AddJsonFile("appsettings.json", true, true)
      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true)
      .AddOcelot($"{Directory.GetCurrentDirectory()}/Config", env)
      .AddEnvironmentVariables();

builder.Services
    .AddOcelot()
    .AddPolly()
    .AddCacheManager(x =>
    {
        x.WithDictionaryHandle();
    })
    .AddConsul();
//.AddConfigStoredInConsul();//AddConfigStoredInConsul:ocelot配置内容可以在consul界面修改及时生效可视化管理配置

builder.Services.Configure<JwtConfig>(conf.GetSection("JwtConfig"));
var jwtConfig = builder.Services.BuildServiceProvider().GetService<IOptionsSnapshot<JwtConfig>>().Value;

builder.Services.AddAuthentication().AddJwtBearer("Bearer", options =>
{
    options.TokenValidationParameters = JwtTokenHelper.GenarateTokenValidationParameters(jwtConfig);
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();

    var serviceRoters = conf.GetSection("Routes")
        .Get<List<ServiceRouter>>()
        .Select(p=>p.ServiceName)
        .Distinct()
        .ToList();

    app.UseSwaggerUI(options =>
    {
        serviceRoters.ForEach(m =>
        {
            //serviceInfo 需要优化===》m.Replace(".api","")
            options.SwaggerEndpoint($"/{m.Replace(".api","")}/swagger/v1/swagger.json", m);
        });
    });
}

app.UseStaticFiles()
   .UseRouting()
   .UseEndpoints(endpoints =>
   {
       endpoints.MapGet("/", async context =>
       {
           var content = app.GetDefaultPageContent();
           context.Response.Headers.Add("Content-Type", "text/html");
           await context.Response.WriteAsync(content);
       });
   });

app.Urls.Add("http://localhost:5000");

app.UseOcelot().Wait();

app.Run();
